/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BARecentSearchesDataSource.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 10/8/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BARecentSearchesDataSource.h"
#import "BARecentSearchQueryCell.h"

@interface BARecentSearchesDataSource(){
    UIColor* evenColor;
    UIColor* unevenColor;
}

@property (nonatomic, strong) NSMutableArray* searchQueries;
@property (nonatomic, strong) NSString *queriesPlistPath;



@end

@implementation BARecentSearchesDataSource


-(id)init{
    self = [super init];
    if (self) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        _queriesPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"queries.plist"];
        _searchQueries = [NSMutableArray arrayWithContentsOfFile:self.queriesPlistPath];
        if (_searchQueries == nil) {
            _searchQueries = [NSMutableArray new];
        }
        evenColor = [UIColor colorWithWhite:0.90 alpha:1];
        unevenColor = [UIColor colorWithWhite:0.95 alpha:1];
        
    }
    return self;
}

-(void)setTableView:(UITableView *)tableView{
    _tableView = tableView;
    //[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [tableView registerNib:[UINib nibWithNibName:@"BARecentSearchQueryCell" bundle:nil] forCellReuseIdentifier:@"cell"];
}

-(void)addSearchQuery:(NSString*)query{
    for (NSString* q in self.searchQueries) {
        if ([q.uppercaseString isEqualToString:query.uppercaseString]) {
            [self.searchQueries removeObject:q];
            break;
        }
    }
    
    [self.searchQueries insertObject:query atIndex:0];
    if (self.searchQueries.count > 50) {
        NSRange range;
        range.location = 50;
        range.length = self.searchQueries.count - 50;
        [self.searchQueries removeObjectsInRange:range];
    }
    
    [self.searchQueries writeToFile:self.queriesPlistPath atomically:YES];
    
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchQueries.count;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 35;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BARecentSearchQueryCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    [cell.queryLabel setText:[self.searchQueries objectAtIndex:indexPath.row]];
    if (indexPath.row % 2 == 0) {
        [cell.contentView setBackgroundColor:evenColor];
    } else{
        [cell.contentView setBackgroundColor:unevenColor];
    }
    
    return cell;
    
}

// Override to support conditional editing of the table view.
// This only needs to be implemented if you are going to be returning NO
// for some items. By default, all items are editable.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.searchQueries removeObjectAtIndex:indexPath.row];
        [self.searchQueries writeToFile:self.queriesPlistPath atomically:YES];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
        NSMutableArray* indexPaths = [NSMutableArray new];
        for (int i=indexPath.row; i<self.searchQueries.count; i++) {
            [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:indexPath.section]];
        }
        [tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"Slet";
}


#pragma mark UITableViewDelegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.delegate didSelectRecentSearchQuery:[self.searchQueries objectAtIndex:indexPath.row]];
}


@end
